import { Layout as AntLayout } from "antd";
import * as React from "react";
import { connect } from "react-redux";
import { Route, Switch, withRouter } from "react-router-dom";
import style from "./style.module.less";
import genisisCreater from "../container/genisis";
import { isNil } from "lodash";
const { Content } = AntLayout;

export default async options => {
  const seeds = await genisisCreater(options);
  class Router extends React.Component<any, any> {
    public props: any;
    constructor(props) {
      super(props);

      const { session, menus, match } = this.props;
      if (!session || !session.id) {
        this.props.history.push("/login");
        return;
      }
      const menuRouter = menus
        ? menus
            .filter(r => seeds[r.pattern])
            .map((r, i) => {
              // flatMenu 有 id 和 children， id即是后台返回的前端组件的pattern，匹配则渲染router
              const { pattern } = r;
              const { path, component, exact } = seeds[pattern];
              return (
                <Route
                  key={i}
                  path={`${match.url}${path}`}
                  exact={exact}
                  component={component}
                />
              );
            })
        : [];
      const noMenuRouter = Object.keys(seeds)
        .filter(r => r.includes("."))
        .map((r, i) => {
          const { path, component, exact, param = "" } = seeds[r];
          if (isNil(param)) {
            return [
              <Route
                key={`_${i}`}
                path={`${match.url}${path}${param}`}
                exact={exact}
                component={component}
              />
            ];
          } else {
            return [
              <Route
                key={`_${i}`}
                path={`${match.url}${path}${param}`}
                exact={true}
                component={component}
              />,
              <Route
                key={`_${i}`}
                path={`${match.url}${path}`}
                exact={exact}
                component={component}
              />
            ];
          }
        })
        .reduce((a, b) => a.concat(b));

      // const totalRouter = [...menuRouter, ...noMenuRouter];

      /*this.setState({
        routers: [...menuRouter, ...noMenuRouter]
      });*/
      this.state = { router: [...menuRouter, ...noMenuRouter] };
    }

    public render() {
      const { routers } = this.state;
      return (
        <Content className={style.content}>
          <section className={style.wrapper}>
            <Switch>{routers}</Switch>
          </section>
        </Content>
      );
    }
  }

  const mapStateToProps = (store: any) => ({
    menus: store.menus,
    session: store.session
  });

  return connect(mapStateToProps)(withRouter(Router));
};
